<template>
  <div class="app-container">
    <el-form
      ref="queryParams"
      :model="queryParams"
      size="small"
      label-position="right"
      label-suffix=":"
      label-width="120px"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('backOrderLang.backStatus')" prop="backStatus">
            <el-radio-group v-model="queryParams.returnStatus">
              <el-radio-button label="null">{{ $t("all") }}</el-radio-button>
              <el-radio-button
                v-for="item in backStatusOptions"
                :key="item.key"
                :label="item.value"
              >
                {{ $t("statusLang." + item.title) }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item :label="$t('backOrderLang.backType')">
            <el-radio-group v-model="queryParams.returnType">
              <el-radio-button label="null">{{ $t("all") }}</el-radio-button>
              <el-radio-button
                v-for="item in backTypeOptions"
                :key="item.key"
                :label="item.value"
              >
                {{ $t("statusLang." + item.title) }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item>
            <template #label>
              <el-select v-model="noType">
                <el-option
                  :value="0"
                  :label="$t('backOrderLang.backOrderNum')"
                />
                <el-option
                  :value="1"
                  :label="$t('backOrderLang.originalMaterialFlowOrderNum')"
                />
                <el-option
                  :value="2"
                  :label="$t('backOrderLang.originalLogisticsTrackingNum')"
                />
                <el-option
                  :value="4"
                  :label="$t('outboundOrderLang.trackingNo')"
                />
              </el-select>
            </template>
            <el-input
              v-model="anyNo"
              :placeholder="$t('backOrderLang.backPleaseEnterTip')"
              type="textarea"
              :rows="3"
              style="width: 350px"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item
            :label="$t('harvestLang.customerName')"
            prop="customerId"
          >
            <el-select
              v-model="queryParams.customId"
              :placeholder="$t('backOrderLang.userName')"
              clearable
              filterable
              style="width: 400px"
            >
              <el-option
                v-for="item in customerOptionList"
                :key="item.value"
                :value="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item :label="$t('backOrderLang.userName')" prop="customId">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.customId"-->
          <!--              :placeholder="$t('backOrderLang.pleaseEnterTip')"-->
          <!--              clearable-->
          <!--              filterable-->
          <!--              style="width: 400px"-->
          <!--            />-->
          <!--          </el-form-item>-->
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-form-item>
            <template #label>
              <el-select v-model="timeType">
                <el-option :value="0" :label="$t('backOrderLang.createDate')" />
                <el-option :value="1" :label="$t('backOrderLang.backAcceptDate')" />
                <el-option :value="2" :label="$t('backOrderLang.backListingDate')" />
              </el-select>
            </template>
            <el-date-picker
              v-model="timeRange"
              type="daterange"
              value-format="timestamp"
              :start-placeholder="$t('beginDate')"
              :range-separator="$t('to')"
              :end-placeholder="$t('endDate')"
              style="width: 350px"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-search"
            @click="handleQuery"
          >
            {{ $t("query") }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t("reset") }}
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          {{ $t("add") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-download"
          @click="exportToExcel()"
        >
          {{ $t("goodsSKULang.imports") }}</el-button>
      </el-col>
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      border
      class="mt-10"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="$t('tableIndex')"
        type="index"
        :index="indexAdd"
        align="center"
        width="100"
      />
      <el-table-column
        :label="$t('backOrderLang.backInfo')"
        prop="returnNo,providerTrackingNo,outboundNo"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("backOrderLang.backOrderNum") + ":" }}
            <span>{{ scope.row.returnNo }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.originalMaterialFlowOrderNum") + ":" }}
            <span>{{ scope.row.providerTrackingNo
            }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.originalOutNo") + ":" }}
            <span>{{ scope.row.outboundNo }}</span>
          </p>
          <p>
            {{ $t("outboundOrderLang.trackingNo") + ":" }}
            <span>{{ scope.row.trackingNo }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('backOrderLang.userInfo')"
        prop="customName,customId"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("backOrderLang.userName") + ":" }}
            <span>{{ scope.row.customName }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.userId") + ":" }}
            <span>{{ scope.row.customId
            }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('backOrderLang.backType')"
        prop="returnType"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <p>
            <span>{{ $t("statusLang." + getTitleByValue(backTypeOptions, scope.row.returnType)) }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('backOrderLang.backStatus')"
        prop="returnStatus"
        align="center"
        min-width="100"
      >
        <template slot-scope="scope">
          <p>
            <span>{{ $t("statusLang." + getTitleByValue(backStatusOptions, scope.row.returnStatus)) }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('backOrderLang.operateType')"
        prop="operateTypeDesc"
        align="center"
        min-width="100"
      />
      <el-table-column
        :label="$t('backOrderLang.date')"
        prop="gmtCreated,createdUserName"
        align="left"
        min-width="150"
      >
        <template slot-scope="scope">
          <p>
            {{ $t("backOrderLang.createDate") + ":" }}
            <span>{{ scope.row.gmtCreated }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.creator") + ":" }}
            <span>{{ scope.row.createdUserName
            }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.backAcceptDate") + ":" }}
            <span>{{ scope.row.arrivedTime }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.backAcceptPerson") + ":" }}
            <span>{{ scope.row.arrivedUserName
            }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.backListingDate") + ":" }}
            <span>{{ scope.row.shelvedTime }}</span>
          </p>
          <p>
            {{ $t("backOrderLang.backListingPerson") + ":" }}
            <span>{{ scope.row.shelvedUserName
            }}</span>
          </p>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('operation')"
        width="100"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleDetail(scope.row)">
            {{ $t("info") }}
          </el-button>
          <el-button v-if="scope.row.returnStatus == 1" type="text" @click="handleDelete(scope.row)">
            {{ $t("delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <el-pagination
        :total="total"
        layoout="total,prev,pager,next"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        @current-change="pageNoChange"
      />
    </el-row>
    <!-- 新增/编辑弹层 -->
    <DepotBaseForm
      v-model="infoParams.id"
      :visible.sync="depotDialog"
      :title="title"
      :operation="infoParams.operation"
      @close="close"
    />
  </div>
</template>

<script>
import DepotBaseForm from './components/info-form.vue'
import { backStatusOptionDict, backTypeOptionDict } from '@/utils/dictData'
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils'
import { getPageList, backDelete, getImportData } from '@/api/business/operateManage/return'
import { getCustomerNameList } from '@/api/business/inventoryManage/inventory'
import XLSX from 'xlsx';

export default {
  name: 'Depot',
  components: { DepotBaseForm },
  data() {
    return {
      noType: 0,
      anyNo: '',
      timeType: 0,
      timeRange: [],
      customerOptionList: [], // 客户名称下拉
      getTitleByValue: getTitleByValue,
      backStatusOptions: getDictOptionList(backStatusOptionDict),
      backTypeOptions: getDictOptionList(backTypeOptionDict),
      total: 0,
      loading: false,
      queryParams: {
        returnStatus: null,
        returnType: null,
        createdUser: null,
        timeType: null,
        trackingNo: null,
        pageNo: 1,
        pageSize: 10
      },
      tableData: [], // 列表
      infoParams: {
        id: null,
        operation: 0
      },
      depotDialog: false,
      title: ''
    }
  },
  created() {
    this.getDepotPageList()
    this.getCustomerNameList()
  },
  mounted() {
    this.$watch('anyNo', this.convertInput);
  },
  methods: {
    // 获取客户名称下拉
    async getCustomerNameList() {
      const { data } = await getCustomerNameList()
      this.customerOptionList = data
    },
    // 重置
    async handleReset() {
      this.queryParams = {
        returnStatus: null,
        returnType: null,
        createdUser: null,
        pageNo: 1,
        pageSize: 10
      }
      this.noType = 0
      this.anyNo = null
      this.timeRange = []
      await this.$refs.queryParams.resetFields()
      this.getDepotPageList()
    },
    handleOpenInfo(row) {
      this.infoParams.operation = 0
      this.infoParams.id = row.depotId
      this.title = "$t('info')"
      setTimeout(() => {
        this.depotDialog = true
      }, 400)
    },
    // 查询
    async handleQuery() {
      this.queryParams.pageNo = 1
      this.getDepotPageList()
    },
    // 获取列表
    async getDepotPageList() {
      this.loading = true
      const anyNo = this.anyNo
      // 退回单号、原物流商单号、原物流单号、混合条件查询
      this.queryParams.returnNo = undefined
      this.queryParams.providerTrackingNo = undefined
      this.queryParams.outboundNo = undefined
      this.queryParams.blendNum = undefined
      if (this.noType === 0) {
        this.queryParams.returnNo = anyNo
      }
      if (this.noType === 1) {
        this.queryParams.providerTrackingNo = anyNo
      }
      if (this.noType === 2) {
        this.queryParams.outboundNo = anyNo
      }
      if (this.noType === 3) {
        this.queryParams.blendNum = anyNo
      }
      if (this.noType === 4) {
        this.queryParams.trackingNo = anyNo
      }
      // 时间查询
      const timeRange = this.timeRange
      this.queryParams.timeType = undefined
      this.queryParams.startTime = undefined
      this.queryParams.endTime = undefined
      if (timeRange && timeRange.length > 0) {
        const startDate = new Date(timeRange[0])
        const year1 = startDate.getFullYear()
        const month1 = ('0' + (startDate.getMonth() + 1)).slice(-2) // 月份从0开始，需要加1并补零
        const day1 = ('0' + startDate.getDate()).slice(-2) // 提取日期，并补零

        const endDate = new Date(timeRange[1])
        const year2 = endDate.getFullYear()
        const month2 = ('0' + (endDate.getMonth() + 1)).slice(-2)
        const day2 = ('0' + endDate.getDate()).slice(-2)
        this.queryParams.startTime = `${year1}-${month1}-${day1}`
        this.queryParams.endTime = `${year2}-${month2}-${day2}`
        if (this.timeType === 0) {
          this.queryParams.timeType = 'CREATE'
        }
        if (this.timeType === 1) {
          this.queryParams.timeType = 'ARRIVE'
        }
        if (this.timeType === 2) {
          this.queryParams.timeType = 'SHELVED'
        }
      }
      const res = await getPageList({ ...this.queryParams })
      if (res.data) {
        this.tableData = res.data.returnNoRespList
        this.total = res.data.totalRowNum
      } else {
        this.tableData = []
        this.total = 0
      }
      this.loading = false
    },
    // 新增
    async handleAdd() {
      this.infoParams.operation = 1
      this.title = this.$t('add')
      this.depotDialog = true
    },
    // 查看
    async handleDetail(row) {
      this.infoParams.operation = 0
      this.infoParams.id = row.id
      this.title = this.$t('info')
      setTimeout(() => {
        this.depotDialog = true
      }, 400)
    },
    // 删除
    async handleDelete(row) {
      const flag = await this.$confirm(
        this.$t('backOrderLang.deleteTips2'),
        this.$t('backOrderLang.deleteTips1') + '?',
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).catch((err) => err)
      if (flag === 'cancel') return
      const res = await backDelete({ id: row.id })
      if (res && res.returnCode === 10000) {
        this.$message({
          type: 'success',
          message: this.$t('handleSuccess')
        })
        this.getDepotPageList()
      }
    },
    // 关闭弹出层
    close() {
      if (this.infoParams.operation === 1) {
        this.getDepotPageList()
      }
      this.infoParams.id = null
      this.infoParams.operation = 0
      this.depotDialog = false
    },
    // 切换页码
    pageNoChange(newPage) {
      this.queryParams.pageNo = newPage
      this.getDepotPageList()
    },
    indexAdd(index) {
      // console.log(index)
      const page = this.queryParams.pageNo // 当前页码
      const pagesize = this.queryParams.pageSize // 每页条数
      return index + 1 + (page - 1) * pagesize
    },
    convertInput() {
      const inputValues = this.anyNo.split('\n');
      this.anyNo = inputValues.join(' ');
    },
    async exportToExcel() {
      const selectedRows = this.$refs.table.store.states.selection;
      const ids = selectedRows.map(row => row.id);
      if (ids.length === 0) {
        this.$message.warning('请选择需要导出的数据')
        return;
      }
      const res = await getImportData(ids)

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      // 构建表头
      const header = ['退回单号', '原物流商单号', '原出库单号', 'OMS单号', '客户名称', '退件类型', '退件状态', '操作方式', '创建日期', '退件接收日期', '退件上架日期', 'SKU', 'sku件数', 'sku重量', '产品中文名称', '产品英文名称'];
      const dataRows = [];
      let index = 0;
      // 构建数据
      res.data.forEach(item => {
        let returnTypeText;
        switch (item.returnType) {
          case 1:
            returnTypeText = '买家退件';
            break;
          case 2:
            returnTypeText = '服务商退件';
            break;
          case 3:
            returnTypeText = '认领退件';
            break;
          default:
            returnTypeText = '';
        }
        let returnStatusText;
        switch (item.returnStatus) {
          case 1:
            returnStatusText = '在途';
            break;
          case 2:
            returnStatusText = '已到仓';
            break;
          case 3:
            returnStatusText = '已入库';
            break;
          case 4:
            returnStatusText = '已完成';
            break;
          case 5:
            returnStatusText = '已删除';
            break;
          default:
            returnStatusText = '';
        }
        const mainDataRow = [
          item.returnNo,
          item.providerTrackingNo,
          item.outboundNo,
          item.trackingNo,
          item.customerName,
          returnTypeText,
          returnStatusText,
          item.operateTypeDesc,
          item.gmtCreateDate,
          item.arrivalTimeDate,
          item.shelveTimeDate
        ];
        //   item.orderReturnSKUImportVOList.forEach(returnSku =>{
        //     const extendRow =[...mainDataRow,returnSku.skuCode,returnSku.goodsName,returnSku.goodsEnDesc,returnSku.skuNum,returnSku.skuWeight];
        //     dataRows.push(extendRow)
        //   });
        // });
        if (item.orderReturnSKUImportVOList && item.orderReturnSKUImportVOList.length > 0) {
          let firstRow = true;
          item.orderReturnSKUImportVOList.forEach(orderReturn => {
            const extendedRow = firstRow ? [...mainDataRow] : new Array(mainDataRow.length).fill('');
            extendedRow.push(
              orderReturn.skuCode,
              orderReturn.skuNum,
              orderReturn.skuWeight,
              orderReturn.goodsName,
              orderReturn.goodsEnDesc
            );
            dataRows[index++] = extendedRow;
            firstRow = false;
          });
        } else {
          dataRows[index++] = [...mainDataRow]
        }
      })
      const worksheet = XLSX.utils.aoa_to_sheet([header, ...dataRows]);
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
      const columnWidths = {};
      worksheet['!cols'] = [];
      header.forEach((colName, colIndex) => {
        const maxLength = dataRows.reduce((max, row) => Math.max(max, (row[colIndex] || '').toString().length), 0);
        columnWidths[colIndex] = maxLength < 10 ? 10 : maxLength;
        worksheet['!cols'].push({ wch: columnWidths[colIndex] });
      });

      const excelData = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
      const blob = new Blob([new Uint8Array([...excelData].map(c => c.charCodeAt(0)))], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '退件单详情.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }
  }
}
</script>

<style scss="lang" scoped></style>
